﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine.Networking;
using ZyGame.Execute;

namespace ZyGame.Resource
{
    public class CheckUpdateRunnable : Runnable<List<PackageInfo>>
    {
        private string current_module;
        public static CheckUpdateRunnable NoUpdateRequired = new CheckUpdateRunnable();

        public bool EnsureNeedUpdateAssets()
        {
            return result.Count > 0;
        }

        public float GetUpdateLength()
        {
            float size = result.Sum(x => x.length);
            return ((int)((size / 1024f / 1024f) * 100)) / 100f;
        }

        public CheckUpdateRunnable()
        {
            SetResult(new List<PackageInfo>());
        }

        internal static CheckUpdateRunnable Create(string module)
        {
            if (Client.Running.TryGetOrCreate(module, out CheckUpdateRunnable checkUpdateRunnable))
            {
                return checkUpdateRunnable;
            }

            checkUpdateRunnable.current_module = module;
            checkUpdateRunnable.Execute(checkUpdateRunnable.DownloadFileList);
            return checkUpdateRunnable;
        }

        private IEnumerator DownloadFileList()
        {
            string fileListName = AppConfig.GetModuleFileListName(current_module);
            Runnable<string> runnable = Client.Web.Get(AppConfig.GetHotfixAssetPath(fileListName), string.Empty);
            yield return runnable.Waitting();
            if (runnable.EnsureExecutedSuccessful() is false)
            {
                SetResult(new Exception(runnable.result));
                yield break;
            }

            Client.Console.WriteLine("检查资源文件：" + fileListName + " remote:" + runnable.result);
            List<PackageInfo> needUpdateList = new List<PackageInfo>();
            List<PackageInfo> fileList = JsonConvert.DeserializeObject<List<PackageInfo>>(runnable.result);
            if (!Client.File.Exists(fileListName))
            {
                needUpdateList.AddRange(fileList);
            }
            else
            {
                string configData = Client.File.ReadData(fileListName).GetString();
                if (!configData.TryGetJson(out List<PackageInfo> localBuilderConfig))
                {
                    Client.Window.Toast("读取文件列表失败！");
                }
                else
                {
                    Client.Console.WriteLine("对比文件列表！");
                    for (int i = 0; i < fileList.Count; i++)
                    {
                        var temp = localBuilderConfig.Find(x => x.name == fileList[i].name);
                        if (temp is not null && temp.version == fileList[i].version && fileList[i].crc == temp.crc)
                        {
                            continue;
                        }

                        needUpdateList.Add(fileList[i]);
                    }
                }
            }

            Client.Console.WriteLine("update count:" + needUpdateList.Count);
            SetResult(needUpdateList);
        }
    }
}